import md5 from 'md5'
import { login, getUserInfoReq } from '@/api/sys'
import { getItem, setItem, clearItem } from '@/utils/storage'
import { TOKEN } from '@/constant'
import router, { resetRouter } from '@/router'

export default {
  namespaced: true, // 设置为单独模块
  state: () => ({
    token: getItem('token'),
    userInfo: {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      setItem(TOKEN, token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    clearUserInfo(state) {
      state.userInfo = {}
      state.token = ''
    }
  },
  actions: {
    // 登录
    login(context, userInfo) {
      return new Promise((resolve, reject) => {
        // 传递信息, 调取登录接口
        login({
          username: userInfo.username,
          password: md5(userInfo.password)
        })
          .then((data) => {
            // 登录成功
            this.commit('user/setToken', data.token)
            router.push('/')
            resolve('登录成功')
          })
          .catch((err) => {
            // 登录失败
            reject(err)
          })
      })
    },
    // 用户信息
    async getUserInfo(context) {
      const res = await getUserInfoReq()
      this.commit('user/setUserInfo', res)
      return res
    },
    // 退出登录
    loginOut() {
      resetRouter()
      this.commit('user/clearUserInfo')
      clearItem()
      router.push('/login')
    }
  }
}
